package com.example.controller;

import com.example.config.ServiceImpl;
import com.example.demo.Student;
import com.example.impl.MyScheduledJob;
import com.example.impl.StudentMapper;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping
public class StudentController {

    @Autowired
    private ServiceImpl service;
    @GetMapping
    public void select() throws SchedulerException {

// 创建 JobDetail 实例，并与 HelloJob 类绑定
        JobDetail jobDetail = JobBuilder.newJob(MyScheduledJob.class)
                .withIdentity("myJob", "group1")
                .build();

        // 创建 Trigger 实例, 定义该 Job 立即执行, 并且每隔 2 秒钟重复执行一次
        Trigger trigger = TriggerBuilder.newTrigger()
                .withIdentity("myTrigger", "group1")
                .startNow()
                .withSchedule(CronScheduleBuilder.cronSchedule("0/5 * * * * ?"))
                .build();

        // 创建调度器
        Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();

        // 将 job 与 trigger 关联起来放到调度器中
        scheduler.scheduleJob(jobDetail, trigger);

        // 开始执行调度器
        scheduler.start();
    }

    /**
     * 暂停定时任务
     */
    @GetMapping("stop")
    public void close() throws SchedulerException {

        JobKey jobKey = JobKey.jobKey("myJob", "group1");
        Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
        scheduler .pauseJob(jobKey);

    }

    /**
     * 恢复
     */
    @GetMapping("reset")
    public void reset() throws SchedulerException {
        JobKey jobKey = JobKey.jobKey("myJob", "group1");
        Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
        scheduler.resumeJob(jobKey);

    }

    /**
     * 删除
     * @throws SchedulerException
     */
    @GetMapping("remove")
    public void remove() throws SchedulerException {
        JobKey jobKey = JobKey.jobKey("myJob", "group1");
        Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
        scheduler.deleteJob(jobKey);

    }
    @GetMapping("select")
    public Student add(){
     Student student= service.insert();
     return student;
    }
}
